package cn.w.outdoor.lib.media;

import android.media.AudioRecord;
import android.util.Log;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;

import cn.w.outdoor.lib.model.Trans_Package;
import cn.w.outdoor.lib.network.UDPTools;

public class AudioCollector {

    private final static String TAG = "AudioCollector";

    private String remoteIpAddr;
    private int remotePort;
    private OnDataListener dataListener;

    private final AtomicBoolean isStartAudio = new AtomicBoolean(false);

    /**
     * 数据队列，采集到的数据，将直接放在这个队列Buff中间，发送队列将直接从这个队列中间获取数据来发送信息
     */
    private Queue<Trans_Package> bufferQueue;

    public AudioCollector(String remoteIpAddr) {
        this(remoteIpAddr, null);
    }

    public AudioCollector(String remoteIpAddr, OnDataListener dataListener) {
        this.remoteIpAddr = remoteIpAddr;
        this.remotePort = 0x6877;
        this.dataListener = dataListener;
        if (bufferQueue == null) {
            bufferQueue = new ConcurrentLinkedQueue<>();
        }
    }

    public void startAudioCollector() {
        synchronized (isStartAudio) {
            if (!isStartAudio.get()) {
                if (audioCollectorThread == null) {
                    audioCollectorThread = new AudioCollectorThread();
                    audioCollectorThread.start();
                    isStartAudio.set(true);
                }
            } else {
                Log.e(TAG, "startAudioCollector: 音频部分已经初始化，无法再次初始化");
            }
        }
    }

    public void stopAudioCollector() {
        synchronized (isStartAudio) {
            if (isStartAudio.get()) {
                if (audioCollectorThread != null) {
                    audioCollectorThread.stopCollect();
                    try {
                        audioCollectorThread.join();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    audioCollectorThread = null;
                    bufferQueue = null;
                    System.gc();
                    isStartAudio.set(false);
                }
            }
        }
    }

    /**
     * 音频数据采集线程
     */
    private AudioCollectorThread audioCollectorThread;

    /**
     * 音频数据收集线程
     */
    private class AudioCollectorThread extends Thread {

        private boolean stopCollectAudio;

        public void stopCollect() {
            stopCollectAudio = true;
        }

        @Override
        public void run() {
            stopCollectAudio = false;
            int audioBufferSize = AudioRecord.getMinBufferSize(MediaConfig.PCM_AUDIO_SAMPLERATE, MediaConfig.AUDIO_IN_CHANNEL,
                    MediaConfig.AUDIO_FORMAT);
            AudioRecord audioRecord = new AudioRecord(MediaConfig.AUDIO_SOURCE, MediaConfig.PCM_AUDIO_SAMPLERATE,
                    MediaConfig.AUDIO_IN_CHANNEL, MediaConfig.AUDIO_FORMAT, audioBufferSize);
            byte[] buffer = new byte[audioBufferSize];
            int readBufferSize;
            try {

                int readBufferSizeCount = 0;

                audioRecord.startRecording();
                while (!stopCollectAudio) {
                    readBufferSize = audioRecord.read(buffer, 0, buffer.length);
                    if (readBufferSize > 0) {
                        if (readBufferSizeCount % 50 == 0) {
                            Log.e(TAG, "采集到音频数据的长度：" + readBufferSize);
                        }
                        readBufferSizeCount++;
                        byte[] audioBuffer = new byte[readBufferSize];
                        System.arraycopy(buffer, 0, audioBuffer, 0, readBufferSize);
                        Trans_Package trans_package = new Trans_Package(Trans_Package.vType_Audio, audioBuffer);
                        if (dataListener != null) {
                            dataListener.onData(trans_package);
                        }
                        UDPTools.getInstance().sendMediaAsync(trans_package, AudioCollector.this.remoteIpAddr, AudioCollector.this.remotePort);
                    } else {
                        Thread.sleep(1L);
                    }
                }
                Log.e(TAG, "关闭音频采集部分");
                audioRecord.stop();
                audioRecord.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
